package dse.messages.multiversion;

import dse.DataObject;
import dse.DataShare;
import dse.Experiment;
import dse.ExperimentRecorder;
import dse.Node;
import dse.messages.Message;
import dse.messages.MessageHandler;
import dse.messages.MessageSender;
import dse.messages.MessageType;

public class ReadCompleteMessageHandler extends MessageSender implements
		MessageHandler {
	private DataObject dobj;
	private VersionReader reader;
	private boolean multi;
	
	public ReadCompleteMessageHandler(Experiment experiment, DataObject dobj, VersionReader reader, boolean multi)
	{
		super(experiment);
		
		this.dobj = dobj;
		this.reader = reader;
		this.multi = multi;
	}

	@Override
	public boolean acceptMessage(Message message) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void messageInterupted(ExperimentRecorder recorder, Message message,
			double time) {
		// TODO Auto-generated method stub
		//recorder.debug(this, "msgIntrpt: " + message, time);
		//reader.readVersion(recorder, null, time, message.to());
	}

	@Override
	public void messageReceived(ExperimentRecorder recorder, Message message,
			double time) {
		// TODO Auto-generated method stub
		if(ExperimentRecorder.debug)
			recorder.debug(this, "msgRcvd: " + message, time);
		if (message.messageType() != MessageType.ReadComplete) {
			recorder.warn(
					"ReadCompleteMessageHandler recieved " + message.messageType() + " message."
					);
			return;
		}			
		// What do we know about the share?
		Node receiver = message.to();
		
		// Does the receiver have the share?
		DataShare share = receiver.getDataShare(dobj);
		
		if (share != null)
		{
			// Then we need to send a new message BACK (thats why to and from
			// are reversed!
			share.removeCurReads(reader.getTransaction(), multi);
		}
		//else
			//this.messageInterupted(recorder, message, time);
	}
}
